#include "gus2_config.h"
#if GUS2_ENABLE_RX
#include "bytearray.h"
#include <string.h>
#include <memserializer.h>
#include <stdio.h>

bytearray_t* rx_buff_get_bytearray(int size);
typedef int(*rx_state_fnt)(u8 data);

static int _rx_key1(u8 data);
static int _rx_key2(u8 data);

static int _rx_len(u8 data);

static bytearray_t* rx_buffer = NULL;
static rx_state_fnt _rx_state = _rx_key1;
static int _rx_key1(u8 data)
{
	if (data == gusConfig.key1)
	{
		_rx_state = _rx_key2;
		return 0;
	}
	return -1;
}

static int _rx_key2(u8 data)
{
	if (data == gusConfig.key2)
	{
		_rx_state = _rx_len;
		return 0;
	}
	else
	{
		_rx_state = _rx_key1;
		_rx_state(data);
		return -1;
	}
}
#include "gus_crc.h"
static u16 crc = 0;
static int _rx_datas(u8 byte)
{
	int res = byte_array_push_byte_ret_free(rx_buffer, byte);
	if (res >= 2)
	{
		crc16byte(&crc, byte);
	}
	else if (res == 0) //complete
	{
		u16 val = 0;
		memunserializer( rx_buffer->data + rx_buffer->len - 2, "w", &val);
		if (val == crc)
		{
			void rx_msg_queue_push(bytearray_t * ba);
			rx_msg_queue_push(rx_buffer);
		}
		else {
			byte_array_free(rx_buffer);
		}
		rx_buffer = NULL;
		_rx_state = _rx_key1;
	}
	return 0;
}

static int _rx_len(u8 data)
{
	static u8 _rx_len_buffer[4];
	static int index = 0;
	_rx_len_buffer[index++] = data;
	if (index == 4)
	{
        index = 0;
		if (_rx_len_buffer[0] == _rx_len_buffer[2] && _rx_len_buffer[1] == _rx_len_buffer[3])
		{
			int count = _rx_len_buffer[3];
			count = (count << 8) | _rx_len_buffer[2];
			rx_buffer = rx_buff_get_bytearray(count);
			if (rx_buffer == NULL)
			{
				_rx_state = _rx_key1;
				return -2;
			}
			crc = CRC_INI_VAL;
			_rx_state = _rx_datas;
			return 0;
		}
		else
		{
			_rx_state = _rx_key1;
			return -1;
		}
	}
	else
	{
		return 0;
	}
}


int on_rx_byte(u8 data)
{
	return _rx_state(data);
}
#endif 

